import re
import os
from os import popen
from random import choice, randint
import string
import sys
from ldaputils import *
import ldap.modlist

def genPasswd():
    chars = string.letters + string.digits
    newpasswd = ""
    for i in range(8):
        newpasswd += choice(chars)
    return newpasswd


def cryptPassword(password):
    return popen("openssl passwd -1 " + password).read().strip()

class userManager:
    def __init__(self, name, ou, www, mail, description=None, password=None, ssh=False):
        if not ou:
            print "errore nessuna ou specificata"
            sys.exit(0)
        self.ou = ou
        self.name = name
        if not password:
            self.password = genPasswd()
        else:
            self.password = password
 
        self.description = description
        self.www = www
        self.mail = mail

        if mail:
            self.domain = re.search("@(?P<dom>.*)", self.mail).group(1)
        else:
            self.domain = None
        
        if ssh:
            self.ssh = "/bin/bash"
        else:
            self.ssh = "/dev/null"
            
        self.cryptpassword = cryptPassword(self.password)
        self.genUid()
        self.genGid()
        self.makeModlist()

                
    def genUid(self):
        while True:
            self.uid = randint(1001, 2000)
            out = popen("getent passwd | grep " +str(self.uid) + " | awk -F: '{print $3}'").read()
            if not out:
                break
    
    def genGid(self):
        self.gid = self.uid
        while True:
            out = popen("getent group | grep " + str(self.gid) + " | awk -F: '{print $3}'").read()
            if not out:
                break
            else:
                self.gid = randint(1001, 2000) 
                        

    def makeModlist(self):
        oc = ["top", "person", "organizationalPerson", "inetOrgPerson", "posixAccount", "shadowAccount"]
        if self.mail:
            oc += ["postfixUser"]
        if self.www:
            oc += ["apacheConfig"]
        self.umlist = ldap.modlist.addModlist(
        {"uid":str(self.name),
         "cn":str(self.description),
         "sn":str(self.name),
         "objectClass":oc,
         "userPassword":"{crypt}%s"%self.cryptpassword,
         "loginShell":self.ssh,
         "uidNumber":str(self.uid),
         "gidNumber":str(self.gid),
         "homeDirectory":str("/home/%s"%self.name),
        })
        
        if self.mail:
            self.umlist += [('emailContact', str(self.mail))]
        if self.www:
            self.umlist += [("apacheServerName", str(self.www))]
            self.umlist += [("apacheDocumentRoot", str("/home/%s/public_html"%self.name))]
         
        self.gmlist = ldap.modlist.addModlist(
        {"objectClass": ["posixGroup", "top"],
         "cn":str(self.name),
         "gidNumber":str(self.gid)
        })


    def save(self):
        l = ldapConnect()
        if self.ou == "clients":
            dn  = "uid=%s,ou=clients,o="dbsolution sas",dc=localnet,dc=org" %self.name
        else:
            dn  = "uid=%s,ou=%s,ou=people,o="dbsolution sas",dc=localnet,dc=org" %(self.name, self.ou)
        l.add_s(dn, self.umlist)
        
        gdn = "cn=%s,ou=group,o="dbsolution sas",dc=localnet,dc=org"%self.name
        l.add_s(gdn, self.gmlist)
        
        self.createDirectory()

    def createDirectory(self):
        home = "/home/%s" %self.name
        if not os.access(home, os.F_OK):
            popen("ldapmanager/apps/core/utility/users home %s %s %s" %(self.name, self.uid, self.gid)).read()
            #os.mkdir(home)
            #os.chown(home, self.uid, self.gid)
        
        fp = open("ldapmanager/apps/core/utility/dirskel.user", "r")
        if fp:
            for f in fp.readlines():
                perm = None
                if not re.search("^/", f):
                    perm = re.search("(?P<perm>[0-9]{4})", f).group(1)
                    f = re.search(":(?P<dir>.*)", f).group(1)
                
                link = ""
                if re.search(" -> ", f):
                    l = re.search("(?P<dir>.*) -> (?P<link>.*)", f)
                    link = l.group('link')
                    f = l.group('dir')

                f = re.sub("\$name", self.name, f)                
      
                if not os.access(home + f.strip(), os.F_OK):
                    popen("ldapmanager/apps/core/utility/users dir %s %s %s %s" %(self.name, f.strip(), self.uid, self.gid)).read()
                    '''
                    os.mkdir(home + f.strip())
                    os.chown(home + f.strip(), self.uid, self.gid)
                    if perm:
                        popen("chmod %s %s" %(perm, home + f.strip()))
                        perm = None       
 
                    if link:
                        os.symlink(home + f.strip(), home + link)
                    '''    
            fp.close()


